/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JFrameEmprestimo.java
 *
 * Created on 24/06/2011, 14:33:21
 */
package br.unesp.demac.bcc.soo.clarus.view;

import br.unesp.demac.bcc.soo.clarus.bean.Aluno;
import br.unesp.demac.bcc.soo.clarus.bean.Emprestimo;
import br.unesp.demac.bcc.soo.clarus.bean.Obra;
import br.unesp.demac.bcc.soo.clarus.dao.AlunoDAO;
import br.unesp.demac.bcc.soo.clarus.dao.AlunoDAOImp;
import br.unesp.demac.bcc.soo.clarus.dao.EmprestimoDAO;
import br.unesp.demac.bcc.soo.clarus.dao.EmprestimoDAOImp;
import br.unesp.demac.bcc.soo.clarus.dao.ObraDAO;
import br.unesp.demac.bcc.soo.clarus.dao.ObraDAOImp;
import br.unesp.demac.bcc.soo.clarus.util.FrameUtil;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListModel;

/**
 *
 * @author Administrador
 */
public class JFrameEmprestimo extends javax.swing.JFrame {

    /** Creates new form JFrameEmprestimo */
    public JFrameEmprestimo() {
        initComponents();
        FrameUtil.centralizar(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblTitle = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        txtRA = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtObra = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstObras = new javax.swing.JList();
        btnAddObra = new javax.swing.JButton();
        btnRemoveObra = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        btnNext = new javax.swing.JButton();
        btnRest = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        txtNomeAluno = new javax.swing.JTextField();
        btnValidaRA = new javax.swing.JButton();
        lbValid = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Empréstimo");
        setResizable(false);

        lblTitle.setFont(new java.awt.Font("Calibri", 1, 18));
        lblTitle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unesp/demac/bcc/soo/clarus/imagens/icon_retirada.png"))); // NOI18N
        lblTitle.setText("Cadastrar Empréstimo");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel1.setText("RA:");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Obras", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setText("Identificação:");

        txtObra.setEnabled(false);
        txtObra.setMinimumSize(new java.awt.Dimension(6, 30));

        lstObras.setEnabled(false);
        lstObras.setMinimumSize(new java.awt.Dimension(33, 30));
        jScrollPane2.setViewportView(lstObras);

        btnAddObra.setText("+");
        btnAddObra.setEnabled(false);
        btnAddObra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddObraActionPerformed(evt);
            }
        });

        btnRemoveObra.setText("-");
        btnRemoveObra.setEnabled(false);
        btnRemoveObra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveObraActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
                    .addComponent(txtObra, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnAddObra, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnRemoveObra, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAddObra)
                    .addComponent(jLabel2)
                    .addComponent(txtObra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnRemoveObra)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE))
                .addContainerGap())
        );

        btnNext.setText("Continuar");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        btnRest.setText("Limpar");
        btnRest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRestActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel3.setText("Nome do Aluno:");

        txtNomeAluno.setEditable(false);

        btnValidaRA.setText("Validar");
        btnValidaRA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnValidaRAActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnRest)
                        .addGap(18, 18, 18)
                        .addComponent(btnNext)
                        .addGap(14, 14, 14))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblTitle)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 368, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtRA, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtNomeAluno, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnValidaRA)
                            .addComponent(lbValid))))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitle)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtRA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(btnValidaRA))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(txtNomeAluno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(lbValid))
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNext)
                    .addComponent(btnRest))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnRestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRestActionPerformed
        resetFields();
    }//GEN-LAST:event_btnRestActionPerformed

    private void btnAddObraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddObraActionPerformed
        ObraDAO odao = new ObraDAOImp();
        Obra obra = null;
        
        try {
            obra = odao.getObraById(Integer.parseInt(txtObra.getText()));
        } catch (NumberFormatException numberFormatException) {
            JOptionPane.showMessageDialog(this,
                    "Identificação inválida",
                    "Alerta",
                    JOptionPane.WARNING_MESSAGE);
            txtObra.setText(null);
            txtObra.requestFocus();
            return;
        }

        if (obra != null && !obra.isFlagExcluido() && odao.isDisponivel(obra)) {
            
            obras.add(obra);

            ListModel model = lstObras.getModel();
            DefaultListModel defaultModel = new DefaultListModel();

            if (model.getSize() > 0) {
                for (int i = 0; i < model.getSize(); i++) {
                    defaultModel.add(i, model.getElementAt(i));
                }
                defaultModel.add(model.getSize(), obra.getNomeObra() + " - " + obra.autoresToString());
            } else {
                defaultModel.add(0, obra.getNomeObra() + " - " + obra.autoresToString());
            }

            lstObras = new JList(defaultModel);
            jScrollPane2.setViewportView(lstObras);
        } else {
            JOptionPane.showMessageDialog(this,
                    "Obra indispoível",
                    "Alerta",
                    JOptionPane.WARNING_MESSAGE);
        }
        txtObra.setText(null);
        txtObra.requestFocus();

    }//GEN-LAST:event_btnAddObraActionPerformed

    private void btnValidaRAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnValidaRAActionPerformed
        
        AlunoDAO adao = new AlunoDAOImp();
        try {
            currentAluno = adao.getAlunoByRA(Long.parseLong(txtRA.getText().trim()));
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, 
                    "Erro ao acessar o banco de dados", 
                    "Alerta", 
                    JOptionPane.WARNING_MESSAGE);
        } catch (NumberFormatException e) {
            lbValid.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unesp/demac/bcc/soo/clarus/imagens/NG.png")));
            toggleObraEdit(false);
        }
        
        if (currentAluno != null) {
            txtNomeAluno.setText(currentAluno.getNome());
            lbValid.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unesp/demac/bcc/soo/clarus/imagens/OK.png")));
            toggleObraEdit(true);
        } else {
            lbValid.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unesp/demac/bcc/soo/clarus/imagens/NG.png")));
            toggleObraEdit(false);
        }
    }//GEN-LAST:event_btnValidaRAActionPerformed

    private void btnRemoveObraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveObraActionPerformed
        if (lstObras.getSelectedValue() != null) {
            
            obras.remove(lstObras.getSelectedIndex());
            
            ListModel model = lstObras.getModel();
            DefaultListModel dfm = new DefaultListModel();
            for (int i = 0; i < model.getSize(); i++){
                dfm.add(i, model.getElementAt(i));
            }
            dfm.removeElement(lstObras.getSelectedValue());

            lstObras = new JList(dfm);
            jScrollPane2.setViewportView(lstObras);
        } else {
            JOptionPane.showMessageDialog(this, 
                    "Selecione ao menos uma obra", 
                    "Alerta", 
                    JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnRemoveObraActionPerformed

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
        if (validaForm()) {
            boolean status = false;

            Emprestimo empr = new Emprestimo();
            empr.setDataEmprestimo(new Date());
            empr.setObra(obras);
            empr.setAluno(currentAluno);

            EmprestimoDAO edao = new EmprestimoDAOImp();
            try {
                status = edao.salvarEmprestimo(empr);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, 
                        "Erro ao acessar o banco de dados", 
                        "Alerta", 
                        JOptionPane.WARNING_MESSAGE);
            }

            if (status) {
                JOptionPane.showMessageDialog(this, 
                    "Emprestimo realizado com sucesso!", 
                    "Alerta", 
                    JOptionPane.INFORMATION_MESSAGE);
                resetFields();
            } else {
                JOptionPane.showMessageDialog(this, 
                    "Falha ao registra emprestimo!", 
                    "Alerta", 
                    JOptionPane.WARNING_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnNextActionPerformed

    private void resetFields() {
        txtRA.setText(null);
        txtNomeAluno.setText(null);
        lbValid.setIcon(null);
        
        txtObra.setText(null);
        DefaultListModel defaultModel = new DefaultListModel();
        lstObras = new JList(defaultModel);
        jScrollPane2.setViewportView(lstObras);
        toggleObraEdit(false);
    }
    
    private void toggleObraEdit(boolean st) {
        txtObra.setEnabled(st);
        btnAddObra.setEnabled(st);
        btnRemoveObra.setEnabled(st);
        lstObras.setEnabled(st);
    }
    
    private boolean validaForm() {
        boolean valid = false;
        String errormsg = "";
        if (txtRA.getText().trim().equals("")) {
            errormsg = "Favor preencher o campo RA";
        } else if (currentAluno == null) {
            errormsg = "Favor validar RA";
        } else if (obras.isEmpty()) {
            errormsg = "Favor adicionar pelo menos uma obra";
        } else {
            valid = true;
        }
        
        if (!valid) {
            JOptionPane.showMessageDialog(this, 
                    errormsg, 
                    "Alerta", 
                    JOptionPane.WARNING_MESSAGE);
        }
        
        
        return valid;
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JFrameEmprestimo().setVisible(true);
            }
        });
    }
    
    private Aluno currentAluno = null;
    private List<Obra> obras = new ArrayList<Obra>();
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddObra;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnRemoveObra;
    private javax.swing.JButton btnRest;
    private javax.swing.JButton btnValidaRA;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lbValid;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JList lstObras;
    private javax.swing.JTextField txtNomeAluno;
    private javax.swing.JTextField txtObra;
    private javax.swing.JTextField txtRA;
    // End of variables declaration//GEN-END:variables
}
